﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;

namespace ConsoleTest
{
    public class GetHtml
    {
        #region 请求数据
        /// <summary>
        /// 获取html文本
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string GetHtmlWithUtf(string url, Encoding ec)
        {
            if (!(url.Contains("http://") || url.Contains("https://")))
            {
                url = "https://" + url;
            }
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            req.UserAgent = "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
            req.Accept = "*/*";
            req.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.5");
            req.ContentType = "text/xml";

            string sHTML = string.Empty;
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
                {
                    if (response.ContentEncoding.ToLower().Contains("gzip"))
                    {
                        using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
                        {
                            using (StreamReader reader = new StreamReader(stream, ec))
                            {
                                sHTML = reader.ReadToEnd();
                            }
                        }
                    }
                    else if (response.ContentEncoding.ToLower().Contains("deflate"))
                    {
                        using (DeflateStream stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress))
                        {
                            using (StreamReader reader = new StreamReader(stream, ec))
                            {
                                sHTML = reader.ReadToEnd();
                            }
                        }
                    }
                    else
                    {
                        using (Stream stream = response.GetResponseStream())
                        {
                            using (StreamReader reader = new StreamReader(stream, ec))
                            {
                                sHTML = reader.ReadToEnd();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                // throw ex;
                return "";
            }

            return sHTML;
        }

        #endregion
    }
}
